import { request } from '@/app';
import { getCookie } from '@/utils/cookieUtils';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { ActionType } from '@ant-design/pro-table';
import { Upload, message } from 'antd';
import type { RcFile, UploadChangeParam, UploadFile, UploadProps } from 'antd/lib/upload';
import React, { useEffect, useRef, useState } from 'react';

interface Props {
  callBack: (value: string) => void;
  initialUrl?: string
}

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const UploadImg: React.FC<Props> = (props) => {
  const actionRef = useRef<ActionType>();
  const { callBack, initialUrl } = props;
  const [imageUrl, setImageUrl] = useState<string>(initialUrl ?? '');
  const [loading, setLoading] = useState(false);

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(url);
        callBack(info.file.response.Items[0].ServerFilePath);
      });
    }
  };

  return <Upload
    name="Avatar"
    listType="picture-card"
    className="avatar-uploader"
    showUploadList={false}
    action={request.imgUrl + "/api/Upload/Upload"}
    headers={{ Authorization: `${getCookie("token")}` }}
    beforeUpload={beforeUpload}
    onChange={handleChange}
  >
    {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%', maxHeight: "100px" }} /> : uploadButton}
  </Upload>
}

export default UploadImg
